# +----------------------------------------------------------------------
# | ChatWork智能聊天办公系统
# +----------------------------------------------------------------------
# | 软件声明: 本系统并非自由软件,未经授权任何形式的商业使用均属非法。
# | 版权保护: 任何企业和个人不允许对程序代码以任何形式任何目的复制/分发。
# | 授权要求: 如有商业使用需求,请务必先与版权所有者取得联系并获得正式授权。
# +----------------------------------------------------------------------
# | Author: ChatWork Team <2474369941@qq.com>
# +----------------------------------------------------------------------
import time
from tortoise.expressions import Q

from common.enums.notice import NoticeEnum
from common.utils.urls import UrlUtil
from common.models.users import UserModel
from common.models.draws import DrawsRecordsModel
from apps.admin.schemas.apply.draws import record_schema as schema
from plugins.msg.driver import MsgDriver


class DrawsRecordService:

    @classmethod
    async def lists(cls, params: schema.DrawsRecordSearchIn):
        # 查询条件
        where = DrawsRecordsModel.build_search({
            "=": ["status"],
            "%like%": ["prompt"],
            "datetime": ["start_time|end_time@create_time"]
        }, params.__dict__)

        where.append(Q(engine=params.engine))
        if params.user_sn:
            user = await UserModel.filter(sn=params.user_sn).first().values("id") or {}
            where.append(Q(user_id=user.get("id", 0)))

        # 查询数据
        _model = DrawsRecordsModel.filter(*where).order_by("-id")
        _pager = await DrawsRecordsModel.paginate(
            model=_model,
            page_no=params.page_no,
            page_size=params.page_size
        )

        # 所属用户
        user_ids = [int(item["user_id"]) for item in _pager.lists if item["user_id"]]
        users: dict = await UserModel.queryUserDictsById(user_ids)

        _lists = []
        for item in _pager.lists:
            user = users.get(item["user_id"], {})
            _lists.append(schema.DrawsRecordVo(
                id=item["id"],
                code=item["code"],
                type=item["type"],
                action=item["action"],
                scale=item["scale"],
                prompt_in=item["prompt_in"],
                prompt_en=item["prompt_en"],
                prompt_eq=item["prompt_eq"],
                thumbnail=await UrlUtil.to_absolute_url(item["thumbnail"]),
                image_ref=await UrlUtil.to_absolute_url(item["image_ref"]),
                image_loc=await UrlUtil.to_absolute_url(item["image_loc"]),
                image_url=item["image_url"],
                points=item["points"],
                status=item["status"],
                is_free=item["is_free"],
                fail_reason=item["fail_reason"] or "",
                create_time=item["create_time"],
                user={
                    "sn": user.get("sn", "").strip(),
                    "nickname": user.get("nickname", ""),
                    "mobile": user.get("mobile", ""),
                    "avatar": await UrlUtil.to_absolute_url(user.get("avatar", ""))
                }
            ))

        _pager.lists = _lists
        return _pager

    @classmethod
    async def delete(cls, engine: str, id_: int, reason: str):
        record = await DrawsRecordsModel.filter(engine=engine, id=id_, is_delete=0).get()
        await DrawsRecordsModel.filter(id=id_).update(
            is_delete=1,
            delete_time=int(time.time())
        )

        # 发送用户通知
        await MsgDriver.send(scene=NoticeEnum.DRAW_DELETE, params={
            "user_id": int(record.user_id),
            "code": record.code,
            "type": record.type,
            "prompt": record.prompt_in,
            "reason": reason
        })
